package org.luchengye.ioauth2.clientresttemplate.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService detailsService() {
        return new ClientUserDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        //auth.userDetailsService(detailsService()).passwordEncoder(NoOpPasswordEncoder.getInstance());//旧版本模式，不对密码加密和解密
        auth.userDetailsService(detailsService()).passwordEncoder(passwordEncoder());//新版本模式，对密码加密和解密

        //内存模式
//        auth.inMemoryAuthentication()
//                .passwordEncoder(new BCryptPasswordEncoder())//登陆时用BCrypt加密方式对用户密码进行处理
//                .withUser("luchengye")
//                .password(new BCryptPasswordEncoder().encode("123456"))//对密码进行Bcrypt编码加密
//                .roles("VIP1","VIP2");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers
                (
                        "/",
                        "/index.html",
                        "/registry",
                        "/sign_up"
                )
                .permitAll()
                .anyRequest().authenticated().and()
                .formLogin().and()
                .logout().permitAll().and()
                .csrf().disable();


//        http
//                .headers().frameOptions().disable()
//                .and().authorizeRequests()
//                .antMatchers("/registry").permitAll() // 注册请求不需要验证
//                .antMatchers("/sign_up").permitAll()
//                .anyRequest().authenticated()
//                .and().formLogin().loginPage("/sign_in")
//                .loginProcessingUrl("/login").defaultSuccessUrl("/personal_center",true)
//                .failureUrl("/sign_in?error").permitAll()
//                .and().logout().logoutSuccessUrl("/sign_in").permitAll()
//                .and().csrf().disable();
    }

}
